#!/usr/bin/python
# -*- coding: utf-8 -*-
"""api views
"""
from django.http import Http404, HttpResponse, HttpResponsePermanentRedirect

from net4.models import URL
from net4.common.web.spider import html_detail

def tiny_url(request):
    url = request.REQUEST.get('url', '').strip()
    tiny = request.REQUEST.get('tiny', '').strip()
    if not url:
        raise Http404()
    if tiny:
        query = URL.all()
        query.filter('tiny =', tiny)
        if query.count(1) > 0:
            return HttpResponse('%s exists ' % tiny)
    query = URL.all()
    u = query.filter('url =', url).get()
    if u is None:
        u = URL(url=url, tiny=tiny, tiny_count=1)
    else:
        if u.tiny_count is None:
            u.tiny_count = 2
        else:
            u.tiny_count += 1
    detail = html_detail(u.url)
    if detail:
        u.title = detail.get('title', u'')
        u.description = detail.get('description', u'')
    u.verify()
    u.put()
    return HttpResponse('http://suourl.appspot.com/%s' % u.tiny)

def redirect(request, tiny):
    query = URL.all()
    u = query.filter('tiny =', tiny).get()
    if u.redirect_count is None:
        u.redirect_count = 1
    else:
        u.redirect_count += 1
    u.put()
    return HttpResponsePermanentRedirect(u.url)